<template>
  <el-skeleton v-if="loading" :rows="2" animated class="weather" />
  <div v-else class="weather">
    <div class="weather__header">
      <div class="city">
        <span>{{ weather.province }}{{ weather.city }}</span>
        <Position class="icon" />
      </div>
      <div class="weather__type">
        <Icon class="icon" />
        <span>{{ weather.weather }}</span>
      </div>
    </div>
    <div class="weather__content">
      <span class="temperature">{{ weather.temperature }}°C</span>
      <div>
        <div class="end">
          <div>最高</div>
          <span class="temperature">10°C</span>
        </div>
        <div class="end">
          <div>最低</div>
          <span class="temperature">9°C</span>
        </div>
      </div>
    </div>
    <div class="weather__footer"></div>
  </div>
</template>

<script setup>
import {
  Moon,
  MostlyCloudy,
  PartlyCloudy,
  Position,
  Pouring,
  Sunny
} from '@element-plus/icons-vue';
import { head } from 'lodash';
import { computed, onMounted, ref } from 'vue';

const weather = ref({});

const loading = ref(true);

const Icon = computed(() => {
  switch (weather.value.weather) {
    case '晴':
      return Sunny;
    case '多云':
      return PartlyCloudy;
    case '阴':
      return MostlyCloudy;
    case '雨':
      return Pouring;
    case '雪':
  }
  return Moon;
});

const getWeather = async adcode => {
  const res = await fetch(
    `https://restapi.amap.com/v3/weather/weatherInfo?key=74c80f48eecf7d616e379071d9c8ed9c&city=${adcode}&extensions=base`
  );
  const { lives } = await res.json();

  weather.value = head(lives);
  loading.value = false;
};

const getLocation = async () => {
  const res = await fetch('https://restapi.amap.com/v3/ip?key=39aec445f1609c870ace98ffddff56e3');
  const { status, adcode } = await res.json();

  if (status === '1') {
    await getWeather(adcode);
  }
};

onMounted(() => {
  getLocation();
});
</script>
<style scoped>
@import './index.less';
</style>
